import { hostingStyleStore } from '@/stores/hosting-style-store';
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings';
import { initQiniu, uploadFile } from '@/api/qiniu/upload';
import {
  getUserProfileInfo,
} from '@/api/user.js';
import {
  updateCardInfo
} from '@/api/card.js';
import { reqUpdateProfile } from '@/api/hosting-style';
import { chooseAndCropImg } from '@/utils/media';
import { getToken } from '@/utils/storage';

type Form = Pick<
  HostingStyleProfile,
  'user_headimg' | 'user_qm_name' | 'host_style_phone' | 'wx_qr_code' | 'user_desc' | 'tagList' | 'isDefaultBg' | 'backgroundUrl'
> & {
  sexIndex: '0' | '1';
  region: string[];
};

Page({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store: hostingStyleStore,
    fields: ['profile'],
    actions: ['getProfile'],
  },
  data: {
    newAvatar: '',
    form: {} as Form,
    sexRange: ['男', '女'],
    cardInfo: { //主持人卡片数据
      type: 'hostCard', //类型，死数据
      phone: '',
      rank: '', // 不存在时，不展示用户的具体排名，改为展示金牌主持人
      introduce: '', //主持人简介，为空，则展示 '我是本场互动主持人，有需要联系我'
      switch: '0', // 主持人卡片开关，0为关闭，1为开启；
      yuehunSwitch: '0'
    },
    cardInfoList: []
  },
  onLoad() {
    if (!this.checkLogin()) return;
    this.initData();
    this.initYuehunSwitch();
  },
  /** 检查当前用户是否已经登录，未登录则跳转到首页，并且终止执行 */
  checkLogin() {
    if (!getToken()) {
      wx.switchTab({
        url: '/pages/index/index',
      });
      return false;
    }

    return true;
  },
  async initData() {
    if (!this.data.profile.isGetProfile) {
      await this.getProfile();
      await new Promise((resolve) => wx.nextTick(resolve));
    }

    const region = (() => {
      const { user_province, user_city } = this.data.profile;
      const region = [];
      if (user_province) {
        region.push(user_province);
      }
      if (user_city) {
        region.push(user_city);
      }
      return region;
    })();

    this.setData({
      form: {
        user_headimg: this.data.profile.user_headimg,
        user_qm_name: this.data.profile.user_qm_name,
        host_style_phone: this.data.profile.host_style_phone,
        wx_qr_code: this.data.profile.wx_qr_code,
        user_desc: this.data.profile.user_desc,
        tagList: this.data.profile.tagList,
        isDefaultBg: this.data.profile.isDefaultBg,
        backgroundUrl: this.data.profile.backgroundUrl,
        sexIndex: this.data.profile.user_sex === '1' ? '0' : '1',
        region,
      },
    });
  },
  onClickAvatar(e: WechatMiniprogram.TouchEvent) {
    const src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
  async onClickAvatarEdit() {
    const cropImg = await chooseAndCropImg();
    this.setData({
      'form.user_headimg': cropImg,
    });
  },
  onSexChange(e: WechatMiniprogram.PickerChange) {
    this.setData({
      'form.sexIndex': e.detail.value,
    });
  },
  onRegionChange(e: WechatMiniprogram.PickerChange) {
    this.setData({
      'form.region': e.detail.value,
    });
  },
  onClickQrCode(e: WechatMiniprogram.TouchEvent) {
    const qrCodeUrl = e.currentTarget.dataset.qrCodeUrl;
    wx.navigateTo({
      url: '/subpkg/pages/add-personal-qr-code/add-personal-qr-code?qrCodeUrl=' + qrCodeUrl,
      events: {
        deleteQrCode: () => {
          this.setData({
            'form.wx_qr_code': '',
          });
        },
        addQrCode: (qrCodeUrl: string) => {
          this.setData({
            'form.wx_qr_code': qrCodeUrl,
          });
          console.log('edit-profile addQrCode', qrCodeUrl);
          console.log('edit-profile form', this.data.form);
        },
      },
    });
  },
  onClickIntroduction() {
    const dialog = this.selectComponent('#edit-introduction-dialog');
    console.log('dialog', dialog);
    dialog.open();
  },
  onConfirmIntroductionDialog(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      'form.user_desc': e.detail.value,
    });
  },
  onClickTag() {
    wx.navigateTo({
      url: '/subpkg/pages/edit-tag/edit-tag?selectedTagList=' + JSON.stringify(this.data.form.tagList),
      events: {
        updateTags: (tagList: string[]) => {
          this.setData({
            'form.tagList': tagList,
          });
        },
      },
    });
  },
  async onClickBackground() {
    const cropImg = await chooseAndCropImg();

    this.setData({
      'form.backgroundUrl': cropImg,
    });
  },
  validateForm(form: Form) {
    if (!form.user_qm_name) {
      wx.showToast({ title: '请填写姓名', icon: 'none' });
      return false;
    }
    return true;
  },
  async onSubmit(e: WechatMiniprogram.FormSubmit) {
    const form: Form = {
      ...this.data.form,
      ...e.detail.value,
    };
    console.log('form', form);

    if (!this.validateForm(form)) return;

    const imgList = [
      {
        key: 'user_headimg',
        value: form?.user_headimg || '',
      },
      {
        key: 'wx_qr_code',
        value: form?.wx_qr_code || '',
      },
      {
        key: 'backgroundUrl',
        value: form.backgroundUrl,
      },
    ].filter((img) => img.value && !img.value.startsWith('https://ustatic'));

    if (imgList.length) {
      await initQiniu();
      const uploadRes = await uploadFile(imgList.map((img) => img.value));
      imgList.forEach((img, index) => {
        // @ts-ignore ts无法正常推断img.key只能是user_headimg、wx_qr_code、backgroundUrl
        form[img.key] = uploadRes[index].fileURL;
      });
    }
    const user_city = form.region?.[form.region.length - 1] || '';
    const user_province = form.region.length > 1 ? form.region[0] : '';
    const res = await reqUpdateProfile({
      host_style_phone: form.host_style_phone,
      host_style_sign: form.tagList.join(','),
      user_city,
      user_desc: form.user_desc,
      user_headimg: form.user_headimg,
      user_lbt: JSON.stringify([
        {
          type: 'image',
          mediaPath: form.backgroundUrl,
        },
      ]),
      user_province,
      user_qm_name: form.user_qm_name,
      user_sex: form.sexIndex === '0' ? '1' : '2',
      wx_qr_code: form.wx_qr_code,
    });

    if (res?.code === 200) {
      wx.showToast({ title: '保存成功' });
      this.getProfile();
      wx.navigateBack();
    }
  },
  async changeYuehunSwitch(e: WechatMiniprogram.SwitchChange) {
    this.setData({
      'cardInfo.yuehunSwitch': e.detail.value ? '1' : '0'
    });
    this.data.cardInfoList.forEach((cardInfo:any) => {
      if(cardInfo.type === 'hostCard') {
        cardInfo.yuehunSwitch = this.data.cardInfo.yuehunSwitch
      }
    });
    const cardJson = JSON.stringify(this.data.cardInfoList);
    wx.showLoading({
      title: '请求中...',
      mask: true
    });
    await updateCardInfo(cardJson);
    wx.hideLoading();
  },
  async initYuehunSwitch() {
    try {
      const {
        data: userInfo
      } = await getUserProfileInfo();
      const { card_json } = userInfo;
      if (!card_json) {
        return;
      }
      const cardInfoList = JSON.parse(card_json);
      this.setData({
        cardInfoList,
      });
      const targetIndex = cardInfoList.findIndex((item: any) => {
        if (item.type === 'hostCard') {
          return true;
        }
        return false;
      });
      if (targetIndex > -1) {
        const hostCard = cardInfoList[targetIndex];
        this.setData({
          'cardInfo.yuehunSwitch': hostCard.yuehunSwitch
        });
        console.log('约婚开关：', this.data.cardInfo.yuehunSwitch);
        
      }
    } catch (err) {
      console.log(err);
    }
  },
});
